import logging
from git import Repo
import os
import sys

logging.basicConfig(level = logging.INFO, format = '%(asctime)s - %(levelname)s - %(filename)s:%(lineno)s - %(message)s')
logger = logging.getLogger()

def create_repo_list(src_dir, repo_list_dir):

    urlPre = "https://gitee.com/"
    
    dirList = os.listdir(src_dir)
    for repoDir in dirList:
        try:
            repo = Repo(os.path.join(src_dir, repoDir))
            remote_url = repo.remote('origin').url.replace(urlPre,"").replace(".git","")
            commit = repo.head.commit.hexsha
            branch = repo.active_branch.name
            line = remote_url + " " + repoDir + " " + commit + " " + branch + "\n"

            with open(repo_list_dir, 'a+') as f:
                f.write(line)
        except Exception as e:
            continue
    

def create_manifest(src_dir):

    if os.path.exists(os.path.join(src_dir,"manifest.xml")):
        os.remove(os.path.join(src_dir,"manifest.xml"))

    code_lines = []
    with open(os.path.join(src_dir, "code.list"), 'r') as f:
        for read_line in f.readlines():
            if read_line != "":
                code_lines.append(read_line.replace("\n","".replace("\r","")))

    with open(os.path.join(src_dir, 'manifest.xml'), 'a+') as f:
        f.write('<?xml version="1.0" encoding="utf-8"?>\n')
        f.write('<manifest>\n')
        f.write('    <remote name="gitee" fetch="https://gitee.com/" review="https://gitee.com/"/>\n')
        f.write('    <default revision="${SRC_BRANCH}" remote="gitee" sync-j="8"/>\n')

        for line in code_lines:
            line_split = line.split(" ")
            wline = "    <project name=\"{}.git\" path=\"{}\" revision=\"{}\" groups=\"openeuler\" upstream=\"{}\"/>".format(line_split[0],line_split[1],line_split[2],line_split[3])
            f.write(wline+"\n")

        f.write("</manifest>")


srcDir = sys.argv[1]
if os.path.exists(os.path.join(srcDir, "code.list")):
    os.remove(os.path.join(srcDir, "code.list"))

os.mknod(os.path.join(srcDir, "code.list"))

create_repo_list(srcDir, os.path.join(srcDir, "code.list"))
create_manifest(srcDir)